<?php

/**
 * Class IndexController
 */
class IndexController extends BaseController{
	public $pro_code1 = array();
    public function init(){
		parent::init();
        $this->module('gpsclient');
		$this->$pro_code1 = config('pro_code1');		
        if(!session:: get('pcorder_api_key')){
			session:: set('pcorder_api_key',$this->get('api_key'),28800);
            $this->redirect($this->_createUrl('index/index',array('api_key'=>'store.kwinbon.grain')));
        }
        Gpsclient::factory(BaseController::$api_key,'123213123124');	

        if(!LoginHelper::getUserId()){
            $this->redirect($this->_createUrl('passport/login'));
        }
        $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
        $cart_nums = $cart_model->count('t_26_user_product_cart_list', "1", array('user_id'=>LoginHelper::getUserId()));
        $this->assign('cart_nums',$cart_nums);
        //头条消息
        $notice_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_info');
        $lastMessages = $notice_model->where("state=1")->order("insert_dt desc")->limit(1)->select();
        if($lastMessages){
            if($notice_model->count('t_26_notice_read','1',array('notice_id'=>$lastMessages[0]['id'],'user_id'=>LoginHelper::getUserId())) == 0){
                $this->assign('item_msg',$lastMessages[0]);
            }
        }
        $menu_model = BaseController::createMode('db_line6','t_bd_item_info');
        $list_menu = $cart_model->where(array('user_id'=>LoginHelper::getUserId()))->select();
        foreach($list_menu as $key=>$val){
            $merchandises = $menu_model->execute("select top 1 * from t_bd_item_info where item_no='".$val['m_id']."'");
			$merchandise = $merchandises[0];
            if($merchandise){
                $list_menu[$key]['m_name'] = iconv('GBK', 'UTF-8', $merchandise['item_name']);
				$list_menu[$key]['unit_no'] = iconv('GBK', 'UTF-8', $merchandise['unit_no']);
                $list_menu[$key]['m_price'] = $merchandise['scheme_price'];          
                $list_menu[$key]['tag_name'] = $spec_name;
            }
        }
        //菜单导航
        $model_product = BaseController::createMode('db_line6','t_bd_item_cls');
        $first_kind=$model_product->where("cls_parent='' and item_clsno < '03'")->select();
        foreach($first_kind as $key=>$val){
			$first_kind[$key]['item_clsname'] = iconv('GBK', 'UTF-8', $val['item_clsname']);
            //获取子分类信息
			$child_list = array();
            $child_list = $model_product->where("cls_parent='".$val['item_clsno']."'")->select();
			foreach($child_list as $k=>$cl){
				$child_list[$k]['item_clsname'] = iconv('GBK', 'UTF-8', $cl['item_clsname']);
			}
            //添加子分类列表
            $first_kind[$key]['child_list'] = is_array($child_list) ? $child_list : array();
            if(!$first_kind[$key]['child_list']){
                unset($first_kind[$key]);
            }
            foreach($first_kind[$key]['child_list'] as $thkey=>$throw ){
				$three_child_list = array();
                $three_child_list = $model_product->where("cls_parent='".$throw['item_clsno']."'")->select();
				foreach($three_child_list as $kk=>$cll){
					$three_child_list[$kk]['item_clsname'] = iconv('GBK', 'UTF-8', $cll['item_clsname']);
				}
                $first_kind[$key]['child_list'][$thkey]['child_list'] = is_array($three_child_list) ? $three_child_list : array();
            }
        }

	//信息
        $message_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_info');
        $message_total = $message_model->where(array("state"=>1))->count('t_26_notice_info','1');
        $list = $message_model->where(array("state"=>1))->select();

        $read_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_read');
        foreach($list as $key=>$val){
            $merchandise = $read_model->getOne(array('notice_id'=>$val['id'],'user_id'=> LoginHelper::getUserId()));
            if($merchandise){
                $message_total =$message_total- 1;
            }
        }
        $this->assign('message_num',$message_total);
        $this->assign('datas',$list_menu);
        $this->assign('first_kind',$first_kind);
        return true;
    }
    public function indexAction(){
        $model_goods = BaseController::createMode(BaseController::$default_db,'t_26_menu');
        $model_file = BaseController::createMode(BaseController::$default_db,'t_26_attach');
        //t_26_sales_promotion
        $model_hots = BaseController::createMode('db_line6','t_bd_item_info');
        $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
		
		$promotion_model = BaseController::createMode(BaseController::$default_db,'t_26_product_promotion');
        $num=100;
        $hot_goods = $model_hots->execute("select top 100 * from t_bd_item_info where item_clsno like '01%' or item_clsno like '02%' order by build_date desc");
        foreach($hot_goods as $key=>$row){
			$goods_stock = $model_hots->execute("select top 1 * from t_im_branch_stock where item_no = '".$row['item_no']."'");
			$hot_goods[$key]['stock_qty'] = round($goods_stock[0]['stock_qty'],2);
			 $hot_goods[$key]['item_name'] = iconv('GBK', 'UTF-8', $row['item_name']);
			 $hot_goods[$key]['unit_no'] = iconv('GBK', 'UTF-8', $row['unit_no']);
			 $cartinfo=$cart_model->getOne(array('m_id'=>$row['item_no'],'user_id'=>LoginHelper::getUserId()));
				$hot_goods[$key]['cart_total'] = floatval($cartinfo['total']);
		}
        $hot_tabs = array();
        if(is_array($sales_list)){
            $hot_tabs = array_merge($hot_tabs,$sales_list);
        }		
		$hot_ac =array(
            array(
                'title'=>'新品上架',
                'data' => array_slice($hot_goods,0,100),
            )
        );		
		$promotion_titles = $promotion_model->execute("select * from t_26_product_promotion_kind");
		
		foreach($promotion_titles as $kind){			
			$promotion_goods = $promotion_model->where("m_deliver_limit_time > '".date("Y-m-d H:i:s")."'  AND state=1 and kind_id=".$kind['id'])->limit(100)->select();
			foreach($promotion_goods as $key=>$row){
				Log::write('promotion_goods: '.json_encode($row));
				$goods = $model_hots->execute("select top 1 * from t_bd_item_info where item_no = '".$row['item_no']."'");
				$promotion_goods[$key] = array_merge($promotion_goods[$key],$goods[0]);
				 $promotion_goods[$key]['stock_qty'] = $row['m_stock'];
				 $promotion_goods[$key]['m_deliver_limit_time'] = $row['m_deliver_limit_time'];
				 $promotion_goods[$key]['item_size'] = $goods[0]['item_size'];
				 $promotion_goods[$key]['sale_price'] = $goods[0]['sale_price'];
				 $promotion_goods[$key]['current_price'] = $row['price'];
				 $promotion_goods[$key]['item_no'] = $goods[0]['item_no'];
				 $promotion_goods[$key]['item_name'] = iconv('GBK', 'UTF-8', $goods[0]['item_name']);
				 $promotion_goods[$key]['unit_no'] = iconv('GBK', 'UTF-8', $goods[0]['unit_no']);
				$cartinfo=$cart_model->getOne(array('m_id'=>$goods[0]['item_no'],'user_id'=>LoginHelper::getUserId()));
				$promotion_goods[$key]['cart_total'] = floatval($cartinfo['total']);
				 
			}
			$hot_ac[] = array(
                'title'=>$kind['title'],
                'data' => array_slice($promotion_goods,0,100),
            );
		}

        $hot_tabs = array_merge($hot_tabs,$hot_ac);

        $advert_model =  BaseController::createMode(BaseController::$default_db,'t_26_guanggaoliebiao');
        $advert_info = $advert_model->where(array('pos'=>1,'type'=>1))->order("create_time desc")->select();
        $this ->assign('advert_info',$advert_info);          
        $this -> assign('hot_tabs',$hot_tabs);
        $this -> display('index');
    }

    public function searchTipsAction(){
		$jPack = "";
         if(isset($_POST["params"])){
             $jPack = $_POST["params"];
         }
         if(isset($_GET["params"])){
             $jPack = $_GET["params"];
         }
         if($jPack){
             $jPack = urldecode($jPack);
             $jPack = stripcslashes($jPack);//过滤特殊字符
         }
        $jPack = str_replace("\\", '\\\\', $jPack);
        $jsonObj = json_decode($jPack);
        if($jsonObj->keyword){
			
            $sql = "select top 50 * from Line6.dbo.t_bd_item_info where  (item_clsno like '01%' or item_clsno like '02%') and  (item_rem  like '%".strtoupper(iconv("utf-8","gbk",$jsonObj->keyword))."%' or item_name  like '%".iconv("utf-8","gbk",$jsonObj->keyword)."%' or item_no like '%".iconv("utf-8","gbk",$jsonObj->keyword)."%') ";
            $promtion_model = BaseController::createMode('db_sys_26_71','t_26_product_promotion');
			$goods_promotion = $promtion_model->execute("select item_no from t_26_product_promotion",true);
			$item_ids = array_column($goods_promotion,'item_no');
			if(count($item_ids)>0){
				//$sql .= " and item_no not in ('".implode("','",$item_ids)."')";
			}
			$model = BaseController::createMode('db_line6','t_bd_item_info');
            $results = $model->execute($sql);
			
            //名字与价格拼接成串
            foreach($results as $key=>$val){				
				$result[$key]['item_name'] = iconv("gbk","utf-8",$val['item_name']);
                $result[$key]['m_name'] = iconv("gbk","utf-8",$val['item_name']);
                $result[$key]['m_usual_price'] = '';
				$result[$key]['item_no'] = $val['item_no'];
				$result[$key]['m_id'] = $val['item_no'];
                $result[$key]['m_group_price'] = '';
            }

            self::$_extensionArray['o']['list'] = $result;
            //TODO 记录搜索历史,注释掉，避免a这种字母也写进我的搜索历史
            if(count($result)>0 && text::isChinese($this->jsonObj->keyword)){
                $modle_history = BaseController::createMode(BaseController::$default_db,'t_26_sousuolishi');
                if($modle_history->getOne(array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id))){
                    $modle_history->update(array('nums'=>'nums+1'),array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id));
                }else{
                    $modle_history->insert(array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id,'nums'=>1));
                }
            }
			self::$_extensionArray['o']['code']=200;
			self::$_extensionArray['o']['task_id'] = $jsonObj->task_id;
			echo json_encode(self::$_extensionArray['o']);exit;
        }else{
            $this->ajax(201,null,array());
        }
    }

	/**
	* 分类页面
	*/
    public function classificationAction(){
		
        //TODO 分页
        $pagesize = 20;
        $page = (int)$this->get('page', 1);
        $pager = $this->instance('pager');
        $pager->loadCss('classic');
        if (!$_GET['page']) {
            $start = 0;
        } else {
            $start = ($_GET['page'] - 1) * $pagesize;
        }
        $class_model = BaseController::createMode('db_line6','t_bd_item_cls');
		 $promtion_model = BaseController::createMode('db_sys_26_71','t_26_product_promotion');
		 $cart_model = BaseController::createMode('db_sys_26_71','t_26_user_product_cart_list');
        if(!$this->get('kid')){
            // $kind = $class_model->where('parent_id=0')->order("item_no asc")->limit(1)->select();
            //$kind2 = $class_model->where('parent_id='.$kind[0]['kind_id'])->order("order_id asc")->limit(1)->select();
            //$kind_id = $kind2[0]['kind_id'];
        }else{
            $kind_id = $this->get('kid');
        }
        $model_goods = BaseController::createMode('db_line6','t_bd_item_info');
        $target = array();
        //$kind_ids = getArrayCidByParentid($class_model, $kind_id,'cls_parent', 'item_clsno',$target);
        array_push($kind_ids,$kind_id);
        $where = " (item_clsno like '".$kind_id."%') and (item_clsno like '01%' or item_clsno like '02%') ";
		$data_total = $model_goods->execute("SELECT COUNT(1) as total_num FROM t_bd_item_info where ".$where);
		
        $data_total = $data_total[0]['total_num'];
		$top_size = $pagesize+$start;
		$goods_promotion = $promtion_model->execute("select item_no from t_26_product_promotion",true);
		$item_ids = array_column($goods_promotion,'item_no');
		if(count($item_ids)>0){
			// $where .= " and item_no not in ('".implode("','",$item_ids)."')";
		}

        $kind_goods = $model_goods->execute("select top $top_size * from t_bd_item_info where ".$where);
        $model_file = BaseController::createMode(BaseController::$default_db,'t_26_attach');
		$kind_goods = array_splice($kind_goods,$start,$pagesize);
		
        foreach($kind_goods as $key=>$row){
			$goods_stock = $model_goods->execute("select top 1 * from t_im_branch_stock where item_no = '".$row['item_no']."'");
			$kind_goods[$key]['item_name'] = iconv('GBK', 'UTF-8', $row['item_name']);
			$kind_goods[$key]['unit_no'] = iconv('GBK', 'UTF-8', $row['unit_no']);
			$kind_goods[$key]['stock_qty'] = round($goods_stock[0]['stock_qty'],2);
			$cartinfo=$cart_model->getOne(array('m_id'=>$row['item_no'],'user_id'=>LoginHelper::getUserId()));
            $kind_goods[$key]['cart_total'] = floatval($cartinfo['total']);
			/**
            $attach = $model_file->getOne(array('m_id'=>$row['m_id']));
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
            $cartinfo=$cart_model->getOne(array('m_id'=>$row['m_id'],'user_id'=>LoginHelper::getUserId()));
            $kind_goods[$key]['cart_total'] = intval($cartinfo['total']);
            $kind_goods[$key]['file_name'] = $attach['file_name'];
			*/
        }
        $model_file->close();
        $params = array();
        if($this->get('kid')){
            $params['kid'] = $this->get('kid');
        }
        $page_url = $this->_createUrl('index/classification',$params)."?page=";
        $pager_html = $pager->total($data_total)->num($pagesize)->page($page)->url($page_url)->output();
        $this->assign('pager_html', $pager_html);
        $this -> assign('kind_goods',$kind_goods);
        $this -> display('classification');
    }

    public function ordersAction(){
        //TODO 分页
        $pagesize = 30;
        $page = (int)$this->get('page', 1);
        $pager = $this->instance('pager');
        if (!$_GET['page']) {
            $start = 0;
        } else {
            $start = ($_GET['page'] - 1) * $pagesize;
        }
        $where = "user_id = ".LoginHelper::getUserId();
        $order = "insert_dt desc";
        if($this->get('ordtime')){
            $ordtime = $this->get('ordtime');
            $where .= " and insert_dt > '".$ordtime."'";
        }
        if($this->get('ordtime_end')){
            $ordtime_end = $this->get('ordtime_end');
            $where .= " and insert_dt < '".$ordtime_end."'";
        }
        $pager->loadCss('classic');
        $orders_model = BaseController::createMode('db_line6','t_pm_sheet_master');
		$where = "branch_no =  ".LoginHelper::getUserId();
		$data_total = $orders_model->execute("SELECT COUNT(1) as total_num FROM t_pm_sheet_master where ".$where);
        $data_total = $data_total[0]['total_num'];
		$top_size = $pagesize+$start;
        $list = $orders_model->execute("select top $top_size * from t_pm_sheet_master where ".$where." order by  work_date desc");
		$list = array_slice($list,$start,$pagesize);
		foreach($list as $key=>$order ){
			$dt = (array)$order['work_date'];
			$list[$key]['order_dt'] = $dt['date'];
			$list[$key]['memo'] = iconv('GBK', 'UTF-8', $order['memo']);
		}
        $params = array();
        $page_url = $this->_createUrl('index/orders',$params)."?page=";
        $pager_html = $pager->total($data_total)->num($pagesize)->page($page)->url($page_url)->output();
        $this->assign('pager_html', $pager_html);
        $this->assign('data',$list);
        $this->display();
    }

    public function accountAction(){
        $orders_model = BaseController::createMode(BaseController::$default_db,'t_26_order_info_financial');
        $where = "user_id = ".LoginHelper::getUserId();
        $order = "insert_dt desc";
        if($this->get('ordtime')){
            $ordtime = $this->get('ordtime');
            $where .= " and insert_dt > '".$ordtime."'";
        }
        if($this->get('ordtime_end')){
            $ordtime_end = $this->get('ordtime_end');
            $where .= " and insert_dt < '".$ordtime_end."'";
        }
        $list = $orders_model->where($where)->order('insert_dt desc')->limit(20)->select();
        $this->assign('data',$list);
        $this->display();
    }

    public function messageAction(){
        //TODO 分页
        $pagesize = 10;
        $page = (int)$this->get('page', 1);
        $pager = $this->instance('pager');
        if (!$_GET['page']) {
            $start = 0;
        } else {
            $start = ($_GET['page'] - 1) * $pagesize;
        }
        $where = "state =1 ";
        if($this->get('ordtime')){
            $ordtime = $this->get('ordtime');
            $where .= " and insert_dt > '".$ordtime."'";
        }
        if($this->get('ordtime_end')){
            $ordtime_end = $this->get('ordtime_end');
            $where .= " and insert_dt < '".$ordtime_end."'";
        }
        $pager->loadCss('classic');
        $message_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_info');
        $data_total = $message_model->where($where)->count('t_26_notice_info','1');
        $list = $message_model->where($where)->order("insert_dt desc")->limit($start,$pagesize)->select();

        $read_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_read');
        foreach($list as $key=>$val){
            $merchandise = $read_model->getOne(array('notice_id'=>$val['id'],'user_id'=> LoginHelper::getUserId()));
            if($merchandise){
                $list[$key]['read'] = 1;
            }else{
                $list[$key]['read'] = 0;
            }
        }

        $params = array();
        $page_url = $this->_createUrl('index/message',$params)."?page=";
        $pager_html = $pager->total($data_total)->num($pagesize)->page($page)->url($page_url)->output();
        $this->assign('pager_html', $pager_html);
        $this->assign('data',$list);
        $this->display();
    }
    public function readNoticeAction(){

        $read_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_read');
        $read_info = $read_model->getOne( array('user_id'=> LoginHelper::getUserId(), 'notice_id'=>$this->post('id')));
        if(empty($read_info)){
            $res = $read_model->insert(array('user_id'=>LoginHelper::getUserId(),'notice_id'=>$this->post('id'), 'insert_dt'=>date("Y-m-d H:i:s")));
        }
        if($res){
            echo json_encode(array('code'=>200,'msg'=>'添加成功'));
        }else{
            echo json_encode(array('code'=>203,'msg'=>'添加失败'));
        }
    }
    public function messagedetailAction(){
        if(!LoginHelper::getUserId()){
            echo json_encode(array('code'=>202,'msg'=>'登录超时'));exit;
        }
        $id = $this->post('id')?$this->post('id'):$this->get('id');
        $message_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_info');
        $red_model = BaseController::createMode(BaseController::$default_db,'t_26_notice_read');
        $read_info = $red_model->getOne( array('user_id'=> LoginHelper::getUserId(), 'notice_id'=>$id));
        if(empty($read_info)){
            $res = $red_model->insert(array('user_id'=>LoginHelper::getUserId(),'notice_id'=>$id, 'insert_dt'=>date("Y-m-d H:i:s")));
        }
        $list = $message_model->where(array('id'=>$id))->select();
        $this->assign('data',$list);
        $this->display();
    }

    public function user_centerAction(){		
        $message_model = BaseController::createMode('db_sys_26_71','t_26_yonghuliebiao');
        $list = $message_model->getOne(array('mobile'=>session:: get('account_oper_id')));
		$model = BaseController::createMode('db_line6','t_bd_branch_info');
		$branch_info = $model->execute("select top 1 * from t_bd_branch_info where branch_no = '".session:: get('account_oper_id')."' ");	
		$branch_info[0]['address'] =  iconv('GBK', 'UTF-8', $branch_info[0]['address']);
		$list = array_merge($list,$branch_info[0]);		
        $this->assign('data',$list);
        if($_POST){
			if($list['password'] != md5($this->post('old_password'))){
				 $this->showMessage("修改失败,原密码不正确",-1,2);
			}
			if(md5($this->post('password')) == md5($this->post('old_password'))){
				 $this->showMessage("修改失败,新密码不能和原密码一样",-1,2);
			}
			$result = $message_model->update(array('password'=>md5($this->post('password'))),array('mobile'=>session:: get('account_oper_id')));
			if($result){
                $this->showMessage("修改成功，正在跳转",$this->_createUrl('passport/login'),2);
            }else{
                $this->showMessage("修改失败,请检查账号是否存在",-1,2);
            }
        }
        $this->display();
    }

    /**
     * 购物车
     */
    public function cartAction(){
        $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
        $m_model = BaseController::createMode('db_line6','t_bd_item_info');
        $list = $cart_model->where(array('user_id'=>LoginHelper::getUserId()))->select();
        foreach($list as $key=>$val){
            $merchandises = $m_model->execute("select * from  t_bd_item_info where item_no='".$val['m_id']."'");
			$merchandise = $merchandises[0];
            if($merchandise){
                $list[$key]['m_name'] = iconv('GBK', 'UTF-8', $merchandise['item_name']);
                //$list[$key]['m_price'] = $val['m_price']; 
				$list[$key]['m_price'] = getProductSalePriceByUserType($merchandise);//检索  					
                $list[$key]['m_min_price'] = $merchandise['base_price'];  
				$list[$key]['chasedo_spec'] = $merchandise['chasedo_spec']; 				
				if($merchandise['unit_no']){
					$list[$key]['tag_name'] = iconv('GBK', 'UTF-8', $merchandise['item_size'].'/'.$merchandise['unit_no']);
				}else{
					$list[$key]['tag_name'] = iconv('GBK', 'UTF-8', $merchandise['unit_no']);
				}              
            }
        }
        $this->assign('data',$list);
        $message_model = BaseController::createMode(BaseController::$default_db,'t_26_yonghuliebiao');
        $messagelist = $message_model->getOne(array('user_id'=>LoginHelper::getUserId()));
        $this->assign('users',$messagelist);
        $this->display();
    }
	
	/**
	**
	**/
	public function refreshGoodsPriceAction(){
		 $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
		 $m_id = $this->post('m_id');
		 if($cart_model->getOne(array('m_id'=>$m_id))){
			 $cart_model->update(
			 array(
				'total'=>$this->post('total'),
				'price'=>$this->post('price'),
				'm_price'=>$this->post('m_price')
			 )
			 ,array('m_id'=>$m_id));
			 
		 }
		
	}
	
	/**
     * 创建订单
     */
    public function createOrderAction(){
        $jPack = $_POST['params']?$_POST['params']:$_GET['params'];
		if($jPack){
             $jPack = urldecode($jPack);
             $jPack = stripcslashes($jPack);//过滤特殊字符
        }
        $jPack = str_replace("\\", '\\\\', $jPack);
		$list = (json_decode($jPack,true));
		$order_model = BaseController::createMode('db_line6','t_pm_sheet_master');
		$order1_model = BaseController::createMode('db_sys_26_71','t_26_order_info');
		$order2_mode2 = BaseController::createMode('db_sys_26_71','t_26_order_product_list');
		$last_order  = $order_model->execute("select top 1 sheet_no from t_pm_sheet_master where branch_no = '".session:: get('account_branch_no')."' order by sheet_no desc ");
		$last_sheet_no = ($last_order[0]['sheet_no']);
		$index = substr($last_sheet_no,2+strlen(session:: get('account_branch_no'))+6);
		$this_index = str_pad((int)$index+1,4,'0',STR_PAD_LEFT);
		$this_order_no = 'DY'.session:: get('account_branch_no').date("ymd").$this_index;
		$model_change = $this->createMode(BaseController::$default_db,'t_26_order_state_change');
		$total_amt=0;
		foreach($list['info'] as $row){
			$merchandises = $order_model->execute("select top 1 * from t_bd_item_info where item_no = '".$row['m_id']."'");
			$total_amt += $row['total']*$row['m_price'];
		}
		$total_amt = round($total_amt,1);
		//判断每个用户每天限制下单		
		if($list){
			$limit_orders = $order1_model->execute("select count(1) as total_num from t_26_order_info where user_id = ".session:: get('account_branch_no')." and insert_dt like '".date("Y-m-d")."%'",false);
			if($limit_orders['total_num']>1  && session:: get('account_branch_no')!='0161'){
				echo json_encode(array('code'=>202,'msg'=>'每天限制1个订单,您已经有'.$limit_orders['total_num'].'个订单了'));exit;//exit;
			}
			$current_time = date("Y-m-d H:i:s");
			$order1_model->insert(array(
				'price'=>$total_amt,
				'orderid'=>$this_order_no,
				'user_id'=>session:: get('account_branch_no'),
				'insert_dt'=>$current_time,
				'truename'=>LoginHelper::getUserName(),
				'address'=>session:: get('account_oper_address'),
				'tel'=>session:: get('account_oper_branch_tel'),
				'deliver_time'=>$list['deliver_time'],
				'buytime'=>time(),
				'remark'=>$list['remark']
			));			
			$sql = "insert into t_pm_sheet_master (sheet_no,sheet_amt,order_amt,trans_no,branch_no,d_branch_no,db_no,branch_flag,approve_flag,oper_date,work_date,valid_date,order_status,memo,oper_id,confirm_man,order_man) values (
			'".$this_order_no."',
			".$total_amt.",
			".$total_amt.",
			'DY',
			'".session:: get('account_branch_no')."',
			'0000',
			'+',
			'".session:: get('account_branch_no')."',
			1,
			'".date("Y-m-d H:i:s")."',
			'".date("Y-m-d H:i:s")."',
			'".date('Y-m-d H:i:s', strtotime('+30days'))."',
			0,
			'".iconv('UTF-8', 'GBK', $list['remark'])."',
			'".session:: get('account_branch_no')."',
			'".session:: get('account_branch_no')."',
			'".session:: get('account_branch_no')."'
			)";	
			if(!$model_change->getOne(array('orderid'=>$this_order_no,'title'=>'您的订单提交成功'))){
				$model_change->insert(
				array(
				'orderid'=>$this_order_no,
				'title'=>'您的订单提交成功',
				'create_time'=>date("Y-m-d H:i:s"),
				'sate'=>1
				)
				);	
			}					
			//写入订单主表
			if($order_model->execute($sql)){
				//写入订单明细表
				foreach($list['info'] as $row){
					$row['price'] = $row['m_price'];
					$merchandises = $order_model->execute("select top 1 * from t_bd_item_info where item_no = '".$row['m_id']."'");
					//$row['price'] = ($row['price']/($row['total']/$merchandises[0]['chasedo_spec']));					
					 $sql = "insert into t_pm_sheet_detail (sheet_no,item_no,memo,sub_amt,sale_price,valid_price,real_qty,produce_date) values (
						'".$this_order_no."',
						'".$row['m_id']."',
						'".iconv('UTF-8', 'GBK', $row['remark'])."',						
						".($row['total']*$row['price']).",
						".$row['price'].",
						".$row['price'].",
						".$row['total'].",
						'".date("Y-m-d H:i:s")."'
					)";
					$order_model->execute($sql);
					$order2_mode2->insert(array(
						'price'=>($row['total']*$row['price']),
						'total'=>$row['total'],
						'm_id'=>$row['m_id'],
						'orderid'=>$this_order_no,
						'user_id'=>session:: get('account_branch_no'),
						'time'=>time(),
						'remark'=>$row['remark']
					));
				}
			}
			echo json_encode(array('code'=>200));
		}else{
			echo json_encode(array('code'=>201));
		}
		
		exit;
    }
	
    /**
     * 我的收藏
     */
    public function collectAction(){
        $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_70_collection');
        $m_model = BaseController::createMode('db_line6','t_bd_item_info');
        $list = $cart_model->where(array('user_id'=>LoginHelper::getUserId()))->select();
        foreach($list as $key=>$val){
            $merchandises = $m_model->execute("select * from t_bd_item_info where item_no = '".$val['c_id']."'");
			$merchandise = $merchandises[0];
            if($merchandise){
                $list[$key]['m_name'] =  iconv('GBK', 'UTF-8', $merchandise['item_name']);
                $list[$key]['m_price'] = getProductSalePriceByUserType($merchandise);
				$list[$key]['sale_price'] = round($merchandise['sale_price'],2);
				$list[$key]['tag_name'] = $merchandise['unit_no'].$merchandise['item_size'];
                $list[$key]['m_group_price'] = $merchandise['m_group_price'];
				$list[$key]['chasedo_spec'] = $merchandise['chasedo_spec'];
				$list[$key]['item_size'] = $merchandise['item_size'];
				$list[$key]['unit_no'] = iconv('GBK', 'UTF-8', $merchandise['unit_no']);
                $spec_name = getProductSpecName($merchandise['m_spec']);
                if($merchandise['tag_name']){
                    $spec_name = $merchandise['tag_name'].'/'.$spec_name;
                }
                $list[$key]['tag_name'] = $spec_name;
            }
        }
        $this->assign('data',$list);
        $message_model = BaseController::createMode(BaseController::$default_db,'t_26_yonghuliebiao');
        $messagelist = $message_model->getOne(array('user_id'=>LoginHelper::getUserId()));
        $this->assign('users',$messagelist);
        $this->display();
    }
    /**
     * 添加至我的收藏
     */
    public function addCollectAction(){
        if($_POST){
            if(!LoginHelper::getUserId()){
                echo json_encode(array('code'=>202,'msg'=>'登录超时'));exit;
            }
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_70_collection');
            $cart_info = $cart_model->getOne( array('user_id'=> LoginHelper::getUserId(), 'c_id'=>$this->post('c_id')));
            if(empty($cart_info)){
                $res = $cart_model->insert(array('user_id'=>LoginHelper::getUserId(),'c_id'=>$this->post('c_id'),'nums'=>$this->post('nums'), 'update_time'=>time()));
            } else {
                $res = $cart_model->update(array(
                    'update_time'=>time(),
                    'nums'=>$cart_info['nums']+$this->post('nums'),
                ),array(
                    'user_id'=> LoginHelper::getUserId(),
                    'c_id'=>$this->post('c_id')
                ));
            }

            if($res){
                echo json_encode(array('code'=>200,'msg'=>'添加成功'));
            }else{
                echo json_encode(array('code'=>203,'msg'=>'添加失败'));
            }
            $cart_model->close();
        }
        exit;
    }

    /**
     * 删除我的收藏
     */
    public function delCollectAction(){
        if($_POST){
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_70_collection');
            $map['user_id'] = $this->post('user_id');
            $map['c_id'] = $this->post('c_id');
            if($cart_model->delete($map)){
                echo json_encode(array('code'=>200));
            }else{
                echo json_encode(array('code'=>201));
            }
            $cart_model->close();
        }
        exit;
    }

    /**
     * 查找购物车
     */
    public function seclectCartAction(){
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
            $menu_model = BaseController::createMode('db_line6','t_bd_item_info');
            $list_menu = $cart_model->where(array('user_id'=>LoginHelper::getUserId()))->select();
            foreach($list_menu as $key=>$val){
				$prodcuts = $menu_model->execute("select top 1 * from t_bd_item_info where item_no = '".$val['m_id']."' ");
                $merchandise = $prodcuts[0];
                if($merchandise){
                    $list_menu[$key]['m_name'] = iconv('GBK', 'UTF-8', $merchandise['item_name']);
					$list_menu[$key]['item_name'] = iconv('GBK', 'UTF-8', $merchandise['item_name']);
                    $list_menu[$key]['m_price'] = $merchandise['sale_price'];
					$list_menu[$key]['m_min_price'] = $merchandise['base_price'];
                    $spec_name = $merchandise['unit_no'].$merchandise['item_size'];                  
                    $list_menu[$key]['tag_name'] = $spec_name;
                    $list_menu[$key]['tag_name'] = $spec_name;
                }
            }
            if($list_menu){
                echo json_encode(array('code'=>200,'datas'=>$list_menu));
            }else{
                echo json_encode(array('code'=>201));
            }
            $cart_model->close();

        exit;
    }
    /**
     * 删除购物车
     */
    public function delCartAction(){
        if($_POST){
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
             $map['user_id'] = $this->post('user_id');
            if($this->post('is_all') != 1){
                //清空购物车
                $map['m_id'] = $this->post('m_id');
            }
            if($cart_model->delete($map)){
                echo json_encode(array('code'=>200));
            }else{
                echo json_encode(array('code'=>201));
            }
            $cart_model->close();
        }
        exit;
    }

    /**
     * 添加至购物车
     */
    public function addCartAction(){
		$m_id = $this->post('m_id');
        if($_POST){
            if(!LoginHelper::getUserId()){
                echo json_encode(array('code'=>202,'msg'=>'登录超时'));exit;
            }
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
            $cart_info = $cart_model->getOne( array('user_id'=> LoginHelper::getUserId(), 'm_id'=>$this->post('m_id')));
            if(empty($cart_info)){
                $res = $cart_model->insert(array('user_id'=>LoginHelper::getUserId(),'m_id'=>$m_id,'m_price'=>$this->post('price'),'total'=>$this->post('total'),'price'=>$this->post('price'), 'remark'=>$this->post('remark')?$this->post('remark'):'', 'time'=>time()));
            } else {
				$total = $cart_info['total']+floatval($this->post('total'));
                $res = $cart_model->update(array(
                    'time'=>time(),
                    'total'=>$total,
					'm_price'=>$this->post('price'),
                    'price'=>$this->post('price')*$total,
                    'remark'=>$this->post('remark')?$this->post('remark'):''
                ),array(
                    'user_id'=> LoginHelper::getUserId(),
                    'm_id'=>$this->post('m_id')
                ));
            }
            $cart_nums = $cart_model->count('t_26_user_product_cart_list', "1", array('user_id'=>LoginHelper::getUserId()));
            if($res){
                echo json_encode(array('code'=>200,'msg'=>'添加成功','m_id'=>$m_id,'total'=>$cart_nums));
            }else{
                echo json_encode(array('code'=>203,'msg'=>'添加失败'));
            }
            $cart_model->close();
        }
        exit;
    }
	
	 /**
     * 添加至购物车
     */
    public function addCartOrderAction(){
		$orderid = $this->post('order_id');
        if($_POST){
            if(!LoginHelper::getUserId()){
                echo json_encode(array('code'=>202,'msg'=>'登录超时'));exit;
            }
            $order_model = BaseController::createMode(BaseController::$default_db,'t_26_order_product_list');
            $order_info = $order_model->where( array('orderid'=> $orderid))->select();
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
			foreach($order_info as $row){
				$cart_info = $cart_model->getOne( array('user_id'=> LoginHelper::getUserId(), 'm_id'=>$row['m_id']));
				if(empty($cart_info)){
					$res = $cart_model->insert(
					array(
					'user_id'=>LoginHelper::getUserId(),
					'm_id'=>$row['m_id'],
					'm_price'=>$row['price']/$row['total'],
					'total'=>$row['total'],
					'price'=>$row['price'], 
					'remark'=>$row['remark'], 
					'time'=>time()));
				} else {
					$total = $row['total'];
					$res = $cart_model->update(array(
						'time'=>time(),
						'm_price'=>$row['price']/$row['total'],
						'total'=>$row['total'],
						'price'=>$row['price'], 
						'remark'=>$row['remark'], 
					),array(
						'user_id'=> LoginHelper::getUserId(),
						'm_id'=>$row['m_id']
					));
				}				
			}            
            $cart_nums = $cart_model->count('t_26_user_product_cart_list', "1", array('user_id'=>LoginHelper::getUserId()));
            if($res){
                echo json_encode(array('code'=>200,'msg'=>'添加成功','total'=>$cart_nums));
            }else{
                echo json_encode(array('code'=>203,'msg'=>'添加失败'));
            }
            $cart_model->close();
        }
        exit;
    }

    /**
     * 修改单品数量
     */
    public function updateCartSingleAction(){
        if($_POST){
            $cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');
            if($cart_model->update(array('total'=>$this->post('total')),array('user_id'=>$this->post('user_id'),'m_id'=>$this->post('m_id')))){
                echo json_encode(array('code'=>200));
            }else{
                echo json_encode(array('code'=>201,'msg'=>'更新失败'));
            }
            $cart_model->close();
        }
        exit;
    }

    /**
     * 注销
     */
    public function logoutAction(){
        $this->display();
    }

    public function searchshopAction(){
			$keywords = $this->get('keywords')? $this->get('keywords') : $this->post('keywords');
            $pagesize = 20;
            $page = (int)$this->get('page', 1);
            $pager = $this->instance('pager');
            $pager->loadCss('classic');
            if (!$_GET['page']) {
                $start = 0;
            } else {
                $start = ($_GET['page'] - 1) * $pagesize;
            }
			$item_pinyin = strtoupper($keywords);
			if($item_pinyin){
				$sql = "select top 50 * from Line6.dbo.t_bd_item_info where (item_rem  like '%".strtoupper(iconv("utf-8","gbk",$keywords))."%' or item_name  like '%".iconv("utf-8","gbk",$keywords)."%' or item_no  like '%".iconv("utf-8","gbk",$keywords)."%')  and (item_clsno like '01%' or item_clsno like '02%')";
			}else{
				$sql = "select top 50 * from Line6.dbo.t_bd_item_info where  (item_name  like '%".iconv("utf-8","gbk",$keywords)."%' or item_no  like '%".iconv("utf-8","gbk",$keywords)."%') and (item_clsno like '01%' or item_clsno like '02%')";
			}
            $model = BaseController::createMode('db_line6','t_bd_item_info');
			$promtion_model = BaseController::createMode('db_sys_26_71','t_26_product_promotion');
			$goods_promotion = $promtion_model->execute("select item_no from t_26_product_promotion",true);
			$item_ids = array_column($goods_promotion,'item_no');
			if(count($item_ids)>0){
				//$sql .= " and item_no not in ('".implode("','",$item_ids)."')";
			}
            $results = $model->execute($sql);
            //名字与价格拼接成串
			$cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list'); 
            foreach($results as $key=>$val){	
				$goods_stock = $model->execute("select top 1 * from t_im_branch_stock where item_no = '".$val['item_no']."'");
				$results[$key]['stock_qty'] = round($goods_stock[0]['stock_qty'],2);			
				$results[$key]['item_name'] = iconv("gbk","utf-8",$val['item_name']);
				$results[$key]['unit_no'] = iconv('GBK', 'UTF-8', $val['unit_no']);
                $results[$key]['m_name'] = iconv("gbk","utf-8",$val['item_name']);
                $result[$key]['m_usual_price'] = '';
                $result[$key]['m_group_price'] = '';
				$cartinfo=$cart_model->getOne(array('m_id'=>$val['item_no'],'user_id'=>LoginHelper::getUserId()));
				$results[$key]['cart_total_nums'] = floatval($cartinfo['total']);
            }        
            $params = array();
            if($keywords){
                $params['keywords'] = $keywords;
            }else{
                $params['keywords'] = $keywords;
            }
            $page_url = $this->_createUrl('index/searchshop',$params)."?page=";
            $pager_html = $pager->total($data_total)->num($pagesize)->page($page)->url($page_url)->output();

            $this->assign('pager_html', $pager_html);
            $this -> assign('kind_goods',$results);
            $this -> assign('data_total',$data_total);
            $this->display();
        }


    public function detailAction(){
		$model_goods = BaseController::createMode('db_line6','t_bd_item_info');
		$class_model = BaseController::createMode(BaseController::$default_db,'t_26_product_kind');
		$cart_model = BaseController::createMode(BaseController::$default_db,'t_26_user_product_cart_list');  								
        $this->assign('cart_nums',$cart_nums);
        if(!$this->get('kid')){           
            $kind = $class_model->where('parent_id=0')->order("order_id asc")->limit(1)->select();
            $kind2 = $class_model->where('parent_id='.$kind[0]['kind_id'])->order("order_id asc")->limit(1)->select();
            $kind3 = $class_model->where('parent_id='.$kind2[0]['kind_id'])->order("order_id asc")->limit(1)->select();
            $kind_id = $kind3[0]['kind_id'];
            $class_model->close();
        }else{
            $product_list= BaseController::createMode(BaseController::$default_db,'t_26_order_product_list');
            $kind_id = $this->get('kid');
             $sql_history = "SELECT * FROM t_pm_sheet_detail where sheet_no like 'DY" . LoginHelper::getUserId() . "%' and item_no = '".$kind_id."'";
            $history_list= $model_goods->execute($sql_history);
			foreach($history_list as $key=>$val){	
				$work_date = (array)$val['produce_date'];
				$history_list[$key]['_date'] = $work_date['date'];
			}			
            $sql_sale='SELECT *,sum(total)  as sale_num ,left(FROM_UNIXTIME(time) ,10) as insert_dt FROM `t_26_order_product_list`  where  m_id =' .$kind_id. ' GROUP BY insert_dt limit 10';
            $sale_list=$product_list->execute($sql_sale);
        }       
		$user_cart_list = $cart_model->getOne(array('m_id'=>$kind_id,'user_id'=>LoginHelper::getUserId()));	
		$this -> assign('goods_cart_user_total',round($user_cart_list['total'],2));
        $kind_goods = $model_goods->execute("select * from t_bd_item_info where item_no = '".$kind_id."'");
		$promotion_data = $class_model->execute("select * from t_26_product_promotion where state=1 and m_deliver_limit_time > '".date("Y-m-d H:i:s")."' and  item_no = '".$kind_id."'",false);
		foreach($kind_goods as $key=>$val){				
				$kind_goods[$key]['item_name'] = iconv("gbk","utf-8",$val['item_name']);
				$goods_stock = $model_goods->execute("select top 1 * from t_im_branch_stock where item_no = '".$row['item_no']."'");
				$kind_goods[$key]['stock_qty'] = round($goods_stock[0]['stock_qty'],2);
				$kind_goods[$key]['unit_no'] = iconv('GBK', 'UTF-8', $val['unit_no']);
		}
		$this -> assign('promotion_data',$promotion_data);
        $this -> assign('kind_goods',$kind_goods[0]);
        $this -> assign('sale_list',$sale_list);
        $this -> assign('history_list',$history_list);
        $this->display();
    }
    public function orderdetailExAction(){
        if($this->get('orderid')){
			$model_this_order = $this->createMode('db_sys_26_71','t_26_order_info');
			$model_this_order_product = $this->createMode('db_sys_26_71','t_26_order_product_list');			
			$my_order = $model_this_order->getOne(array('orderid'=>$this->get('orderid')));
			$my_order_product_list = $model_this_order_product->where(array('orderid'=>$this->get('orderid')))->select();		
            $model_order = $this->createMode('db_line6','t_pm_sheet_master');
            $model_menu = $this->createMode('db_line6','t_bd_item_info');
            $order_infos = $model_order->execute("select top 1 * from t_pm_sheet_master where sheet_no='".$this->get('orderid')."'");
			$order = $order_infos[0];
			//var_dump($order);
			$work_date = (array)$order['work_date'];
			$order['order_dt'] = $work_date['date'];
			//var_dump($order);
            $model = $this->createMode('db_line6','t_pm_sheet_detail');
			
            $data = $model->execute("select top 200 * from t_pm_sheet_detail where sheet_no='".trim($order_infos[0]['sheet_no'])."'");
            $model_change = $this->createMode(BaseController::$default_db,'t_26_order_state_change');            
			//拣货
			$jianhuos = $model_order->execute("select top 1 * from t_rf_sheet_master where voucher_no='".$this->get('orderid')."'");
			if($jianhuos){
				$dt = (array)$jianhuos[0]['oper_date'];
				if(!$model_change->getOne(array('state'=>3,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>'您的订单正在分拣配货',
						'create_time'=>$dt['date'],
						'state'=>3,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			//开始配送
			$diaochu = $model_order->execute("select top 1 * from t_im_sheet_master where voucher_no='".$this->get('orderid')."'");
			if($diaochu){
				$dt = (array)$diaochu[0]['oper_date'];
				if(!$model_change->getOne(array('state'=>4,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>'您的订单已经配货,复核完成',
						'create_time'=>$dt['date'],
						'state'=>4,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			//开始配送
			$diaochu = $model_order->execute("select top 1 * from t_im_sheet_master where voucher_no='".$this->get('orderid')."'");
			//var_dump($diaochu);
			if($diaochu && trim($diaochu[0]['delivery_id']) != '' && trim($diaochu[0]['driver_id']) != ''){
				$dt = (array)$diaochu[0]['oper_date'];
				$driver = $model_order->execute("select top 1 * from t_sys_operator where oper_id='".$diaochu[0]['driver_id']."'");
				
				$delivery = $model_order->execute("select top 1 * from t_sys_operator where oper_id='".$diaochu[0]['delivery_id']."'");
				if(!$model_change->getOne(array('state'=>5,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>"您的订单已经分配给司机:".iconv('gb2312','utf-8',$driver[0]['oper_name']).",送货员:".iconv('gb2312','utf-8',$delivery[0]['oper_name'])."，正在火速赶往您店",
						'create_time'=>$dt['date'],
						'state'=>5,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			$change = $model_change->where(array('orderid'=>$this->get('orderid')))->order("state desc,create_time DESC")->select();
            $ord_nums = 0;
            foreach($data as $key=>$product){
				foreach($data as $rd){
					if(trim($rd['item_no']) == trim($product['m_id'])){
						
						$my_order_product_list[$key]['audit'] = $rd;
					}					
				}
				$my_order_product_list[$key]['audit'] = $product;
				//$row['item_no'] = $product['m_id'];
				$product_list_item = $model_this_order_product->getOne(array('m_id'=>$product['item_no'],'orderid'=>$this->get('orderid')));
				$ord_nums++;
				$m = array();			
                $m = $model_menu->execute("select top 1 * from t_bd_item_info where item_no = '".$product['item_no']."'"); 		
				$my_order_product_list[$key]['item_no'] = 	$product['item_no'];			
                $my_order_product_list[$key]['m_name'] = iconv('gb2312','utf-8',$m[0]['item_name']);
                $my_order_product_list[$key]['m_min_price'] = $product_list_item['m_min_price'];
				$my_order_product_list[$key]['unit_no'] = iconv('gb2312','utf-8',$m[0]['unit_no']);
				$my_order_product_list[$key]['item_size'] = $m[0]['item_size'];
				$my_order_product_list[$key]['memo'] = iconv('gb2312','utf-8',$data[$key]['memo']);
                $my_order_product_list[$key]['m_group_price'] = $product_list_item['m_group_price'];
                $my_order_product_list[$key]['bar_code'] = $product_list_item['bar_code'];
            }
			$this->assign('ord_nums',$ord_nums);
			$this->assign('my_order',$my_order);
            $this->assign('order',$order);
            $this->assign('change',$change);
            $this->assign('data',$my_order_product_list);
        }
        $this->display();
    }

	public function orderdetailAction(){
		$pagesize = 100;
        $page = (int)$this->get('page', 1);
        $pager = $this->instance('pager');
        if (!$_GET['page']) {
            $start = 0;
        } else {
            $start = ($_GET['page'] - 1) * $pagesize;
        }
        if($this->get('orderid')){
			$model_this_order = $this->createMode('db_sys_26_71','t_26_order_info');
			$model_this_order_product = $this->createMode('db_sys_26_71','t_26_order_product_list');			
			$my_order = $model_this_order->getOne(array('orderid'=>$this->get('orderid')));

			$my_order_product_list = $model_this_order_product->where(array('orderid'=>$this->get('orderid')))->select();	
			$pager->loadCss('classic');
			$data_total = $model_this_order_product->execute("SELECT COUNT(1) as total_num FROM t_26_order_product_list where orderid='".$this->get('orderid')."'");
			$data_total = $data_total[0]['total_num'];
			
            $model_order = $this->createMode('db_line6','t_pm_sheet_master');
            $model_menu = $this->createMode('db_line6','t_bd_item_info');
            $order_infos = $model_order->execute("select top 1 * from t_pm_sheet_master where sheet_no='".$this->get('orderid')."'");
			$order = $order_infos[0];
			//var_dump($order);
			$work_date = (array)$order['work_date'];
			$order['order_dt'] = $work_date['date'];
			//var_dump($order);
            $model = $this->createMode('db_line6','t_pm_sheet_detail');
			
            $data = $model->execute("select top 1000 * from t_pm_sheet_detail where sheet_no='".trim($order_infos[0]['sheet_no'])."'");
			//echo "select top 200 * from t_im_sheet_master where voucher_no='".trim($order_infos[0]['sheet_no'])."'";
			$data_im = $model->execute("select top 1000 * from t_im_sheet_master where voucher_no='".trim($order_infos[0]['sheet_no'])."'");
			
			$data2 = $model->execute("select top 1000 * from t_im_sheet_detail where sheet_no='".trim($data_im[0]['sheet_no'])."'");
			//var_dump($data2);
            $model_change = $this->createMode(BaseController::$default_db,'t_26_order_state_change');            
			//拣货
			$jianhuos = $model_order->execute("select top 1 * from t_rf_sheet_master where voucher_no='".$this->get('orderid')."'");
			if($jianhuos){
				$dt = (array)$jianhuos[0]['oper_date'];
				if(!$model_change->getOne(array('state'=>3,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>'您的订单正在分拣配货',
						'create_time'=>$dt['date'],
						'state'=>3,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			//开始配送
			$diaochu = $model_order->execute("select top 1 * from t_im_sheet_master where voucher_no='".$this->get('orderid')."'");
			if($diaochu){
				$dt = (array)$diaochu[0]['oper_date'];
				if(!$model_change->getOne(array('state'=>4,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>'您的订单已经配货,复核完成',
						'create_time'=>$dt['date'],
						'state'=>4,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			//开始配送
			$diaochu = $model_order->execute("select top 1 * from t_im_sheet_master where voucher_no='".$this->get('orderid')."'");
			//var_dump($diaochu);
			if($diaochu && trim($diaochu[0]['delivery_id']) != '' && trim($diaochu[0]['driver_id']) != ''){
				$dt = (array)$diaochu[0]['oper_date'];
				$driver = $model_order->execute("select top 1 * from t_sys_operator where oper_id='".$diaochu[0]['driver_id']."'");
				
				$delivery = $model_order->execute("select top 1 * from t_sys_operator where oper_id='".$diaochu[0]['delivery_id']."'");
				if(!$model_change->getOne(array('state'=>5,'orderid'=>$this->get('orderid')))){
					$model_change->insert(
						array(
						'title'=>"您的订单已经分配给司机:".iconv('gb2312','utf-8',$driver[0]['oper_name']).",送货员:".iconv('gb2312','utf-8',$delivery[0]['oper_name'])."，正在火速赶往您店",
						'create_time'=>$dt['date'],
						'state'=>5,
						'orderid'=>$this->get('orderid')
						)
					);
				}				
			}
			$change = $model_change->where(array('orderid'=>$this->get('orderid')))->order("state desc,create_time DESC")->select();
            $ord_nums = 0;
            foreach($data as $key=>$product){
				foreach($data2 as $rd){
					if(trim($rd['item_no']) == trim($product['item_no'])){
						
						$my_order_product_list[$key]['audit'] = $rd;
					}					
				}
				//$my_order_product_list[$key]['audit'] = $product;
				//$row['item_no'] = $product['m_id'];
				$product_list_item = $model_this_order_product->getOne(array('m_id'=>$product['item_no'],'orderid'=>$this->get('orderid')));
				$ord_nums++;
				$m = array();			
                $m = $model_menu->execute("select top 1 * from t_bd_item_info where item_no = '".$product['item_no']."'");	
				if($_GET[is_debug]==2 && !$m){
					echo "select top 1 * from t_bd_item_info where item_no = '".$product['item_no']."'";
				}
				
				$my_order_product_list[$key]['item_no'] = 	$product['item_no'];						
                $my_order_product_list[$key]['m_name'] = iconv('gb2312','utf-8',$m[0]['item_name']);
                $my_order_product_list[$key]['m_min_price'] = $product_list_item['m_min_price'];
				$my_order_product_list[$key]['unit_no'] = iconv('gb2312','utf-8',$m[0]['unit_no']);
				$my_order_product_list[$key]['item_size'] = $m[0]['item_size'];
				$my_order_product_list[$key]['memo'] = iconv('gb2312','utf-8',$data[$key]['memo']);
                $my_order_product_list[$key]['m_group_price'] = $product_list_item['m_group_price'];
                $my_order_product_list[$key]['bar_code'] = $product_list_item['bar_code'];
            }
				$params = array('orderid'=>$this->get('orderid'));
			$page_url = $this->_createUrl('index/orderdetail',$params)."?page=";
			$pager_html = $pager->total($data_total)->num($pagesize)->page($page)->url($page_url)->output();
			$this->assign('pager_html', $pager_html);
			$this->assign('ord_nums',$ord_nums);
			$this->assign('my_order',$my_order);
            $this->assign('order',$order);
			$this->assign('order_im',$data_im[0]);
            $this->assign('change',$change);
			if($_GET[is_debug]==2){
				echo "<pre>";
				var_export($my_order_product_list);exit;
			}
            $this->assign('data',$my_order_product_list);
        }
        $this->display('orderdetail');
    }
	
    /**
     * 数据同步
     */
    public function syncAction(){
        $sync_last_build_date = '';
        $model_mssql_goods = Controller::createMode('db_line6','t_bd_item_info');
        $merchandise_model = BaseController::createMode(BaseController::$default_db,'t_26_menu');
        $sync_model = BaseController::createMode(BaseController::$default_db,'t_70_sync_log');
        $spec_model = BaseController::createMode(BaseController::$default_db,'t_26_spec_info');
        $model_mssql_class = Controller::createMode('db_line6','t_bd_item_cls');
        $merchandise_kind_model = BaseController::createMode(BaseController::$default_db,'t_26_product_kind');
        //取得上次同步时间
        //TODO 同步品类
        $this->_syncKinds($merchandise_kind_model,$model_mssql_class);
        //TODO 同步商品
        $item_no = "";
        $times = 0;
		if(true){
			do{
				$sync_num = 0;
				$times++;
				$start_time = date("Y-m-d H:i:s");
				if($item_no){
					$sql = "select top 200 * from t_bd_item_info where item_no < '".$item_no."' order by item_no desc";
				}else{
					$sql = "select top 200 * from t_bd_item_info  order by item_no desc";
				}
				if(!$model_mssql_goods){
					$model_mssql_goods = Controller::createMode('db_line6','t_bd_item_info');
				}
				$list = $model_mssql_goods->execute($sql);
				$pinyin = new pinyin();
				foreach($list as $key=>$val){
					$dt_obj = (array)$val['build_date'];
					$sync_last_build_date = $dt_obj['date'];
					$item_no = $val['item_no'];
					$sync_num++;
					$merchandise = $merchandise_model->getOne(array('bar_code'=>$val['item_no']));
					$kind_item = $merchandise_kind_model->getOne(array('kind_code'=>$val['item_clsno']));
					$m_alias = strtolower($pinyin->output(iconv('gb2312','utf-8',$val['item_name'])));
					$m_alias_first = strtolower($pinyin->output(iconv('gb2312','utf-8',$val['item_name']),true,true));
					$m_spec = 0;
					//同步规格
					$spec = $spec_model->getOne(array('spec_name'=>trim(iconv('gb2312','utf-8',$val['unit_no']))));
					if(!$spec){
						$m_spec = $spec_model->insert(array(
							'spec_name'=>trim(iconv('gb2312','utf-8',$val['unit_no']))
						),true);
					}else{
						$m_spec = $spec['spec_id'];
					}
					if(iconv('gb2312','utf-8',$val['unit_no']) != '' && $val['item_size'] != ''){
						$tag_name = "{$val['item_size']}/".iconv('gb2312','utf-8',$val['unit_no']);
					}else{
						$tag_name = $val['item_size']?$val['item_size']:iconv('gb2312','utf-8',$val['unit_no']);
					}
					if($merchandise){
						//update
						$merchandise_model->update(
							array(
								'kind_id'=>$kind_item['kind_id'],
								'm_name'=>iconv('gb2312','utf-8',$val['item_name']),
								'm_desc'=>iconv('gb2312','utf-8',$val['other1']),
								'm_price'=>$val['sale_price'],//配送价/
								'm_min_price'=>$val['price'],//进货价/批发价
								'm_group_price'=>$val['base_price'],//
								'm_alias'=>$m_alias,//
								'state'=>1,//
								'm_spec'=>$m_spec,//
								'm_alias_first'=>$m_alias_first,//
								'tag_name'=>$tag_name,//规格
							),
							array('bar_code'=>$val['item_no'])
						);
					}else{
						$m_id = $merchandise_model->insert(
							array(
								'kind_id'=>$kind_item['kind_id'],
								'm_name'=>iconv('gb2312','utf-8',$val['item_name']),
								'b_id'=>23,//思迅系统
								'm_desc'=>iconv('gb2312','utf-8',$val['other1']),
								'bar_code'=>$val['item_no'],
								'm_price'=>$val['sale_price'],//配送价/
								'm_min_price'=>$val['price'],//进货价/批发价
								'm_group_price'=>$val['base_price'],//
								'm_alias'=>$m_alias,//
								'state'=>1,//
								'm_spec'=>$m_spec,//
								'm_alias_first'=>$m_alias_first,//
								'tag_name'=>$tag_name,//规格
								'insert_dt'=>$dt_obj['date'],
							),true
						);
						$merchandise_model->update(array('group_id'=>$m_id),array('m_id'=>$m_id));
					}
				}
				$end_time = date("Y-m-d H:i:s");
				$sync_model->insert(
					array(
						'sync_start_time'=>$start_time,
						'sync_end_time'=>$end_time,
						'sync_begin_date'=>$sync_last_build_date,
						'sync_end_date'=>$sync_last_build_date,
						'sync_num'=>$sync_num,
						'sync_type'=>2,
					)
				);
			}while(count($list)>0);
		}
    }

    /**
     * 同步图片
     */
    public function syncImageAction(){
        $merchandise_model = BaseController::createMode(BaseController::$default_db,'t_26_menu');
        $attach_model = BaseController::createMode(BaseController::$default_db,'t_26_attach');
        if($this->get('start')){
            $start = $this->get('start');
        }else{
            $start = 0;
        }
        if($this->get('end')){
            $end = $this->get('end');
        }else{
            $end = 200;
        }
        $list = $merchandise_model->limit($start,$end)->select();
        foreach($list as $row){
            echo $file_url = 'http://58.42.241.116:3016/protal/productimg/'.$row['bar_code'].'.jpg ';
            $tempFile = file_get_contents($file_url);
            echo strlen($tempFile)."\r\n<br/>";
            $param = array('op_type'=>1002,
                'user_id'=>1,
                'file_type'=>0,
                'file_length'=>strlen($tempFile),
                'task_id'=>'upload_busi_pic',
            );
            $param = "?json=".json_encode($param);
            $rst   = common::post(Controller::getConfig('service_url').$param, $tempFile);
            $obj = json_decode($rst);
            if (is_object($obj)&&$obj->code==0) {
                //成功
                echo $attach_model->insert(
                    array(
                        'm_id'=>$row['m_id'],
                        'file_type'=>0,
                        'file_name'=>$obj->attach_name,
                    )
                );
            }else{
            }
        }
        exit;
    }

    /**
     *
     * @param $model1 我方数据库模型
     * @param $model2 第三方数据库模型
     * @param null $kind_id1 我方数据库模型
     * @param null $kind_id2 第三方数据库模型
     */
    private function _syncKinds($model1,$model2,$kind_id1 = null,$kind_id2 = null){
            if(!$kind_id2){
                $kinds = $model2->where("cls_parent = ''")->select();
            }else{
                $kinds = $model2->where("cls_parent = '".$kind_id2."'")->select();
            }
            foreach($kinds as $key=>$val){
                $kind = $model1->getOne(array('kind_code'=>$val['item_clsno']));
                if($kind){
                    $model1->update(array(
                        'kind_name'=>iconv('gb2312','utf-8',$val['item_clsname']),
                        'p_desc'=>$val['cls_parent'],
                        'parent_id'=>$kind_id1,
                    ),
                        array('kind_code'=>$val['item_clsno'])
                    );
                    $kind_id = $kind['kind_id'];
                }else{
                    $kind_id = $model1->insert(
                        array(
                            'kind_code'=>$val['item_clsno'],
                            'kind_name'=>iconv('gb2312','utf-8',$val['item_clsname']),
                            'p_desc'=>$val['cls_parent'],
                            'parent_id'=>$kind_id1,
                            'insert_dt'=>date("Y-m-d H:i:s"),
                            'order_id'=>$key+1,
                        ),true
                    );
                }
                $this->_syncKinds($model1,$model2,$kind_id,$val['item_clsno']);
            }
    }
}
